<template>
  <div class="manage-wrap">
    <el-dialog :visible.sync="preview.showPreview" width="80%">
      <answer :onPreviewMode="true" :QID64="preview.previewQID64"></answer>
    </el-dialog>
    <el-container>
      <!-- 侧边导航栏 -->
      <el-container>
        <el-aside width="150px">
          <div class="left-nav-wrap">
            <div class="left-nav">
              <el-button class="nav-button" type="primary" @click="newQuestionnaire">新建问卷</el-button>
              <el-button class="nav-button no-border" :class="{navbuttonactive: isShow===1}"
                @click="showMyQuestionnaire">我的问卷
              </el-button>
              <el-button class="nav-button no-border" :class="{navbuttonactive: isShow===2}" @click="showRecycleBin">
                回收站
              </el-button>
            </div>
          </div>
        </el-aside>
        <!-- 展示区域 -->
        <el-main class="manage-main">
          <div class="sub-header">
            <!-- 卡片/列表切换按钮 -->
            <div class="sub-header-mode fl">
              <span style="margin-left: -1px;" class="sub-header-mode-btn" :class="{active: isActive===1}"
                @click="cardView">
                <i class="iconfont icon-appstore btn-icon" :class="{ btnActive: isActive === 1 }"></i>
              </span>
              <span style="margin-right: -1px" class="sub-header-mode-btn" :class="{active: isActive===2}"
                @click="tableView">
                <i class="iconfont icon-unorderedlist btn-icon" :class="{btnActive: isActive === 2}"></i></span>
            </div>
            <div class="search-input fl">
              <el-input placeholder="请输入问卷名进行搜索..." v-model="searchInput" @keyup.enter.native="search">
                <i slot="suffix" class="el-input__icon el-icon-search" @click="search"></i>
              </el-input>
            </div>
            <div class="sort-mode fl">
              <el-dropdown trigger="hover" @command="handleCommandForTime" class="fl">
                <span class="el-dropdown-link sort-mode-btn">
                  <span class="sort-mode-title">创建时间</span>
                  <i class="el-icon-d-caret"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="a">时间正序</el-dropdown-item>
                  <el-dropdown-item command="b">时间倒序</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-dropdown trigger="hover" @command="handleCommandForCount" class="fl">
                <span class="el-dropdown-link sort-mode-btn">
                  <span class="sort-mode-title">回收量</span>
                  <i class="el-icon-d-caret"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="a">回收量正序</el-dropdown-item>
                  <el-dropdown-item command="b">回收量倒序</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <span class="sort-mode-title fl">排序方式:</span>
            </div>
            <!-- 左侧标题 -->
            <span class="sub-header-title">{{ title }}</span>
          </div>
          <div class="manage-content">
            <!-- 卡片布局 -->
            <div v-show="isActive===1" class="wrap">
              <div v-for="(item,index) in tableData" :key="index">
                <card :my-data="item" :my-index="index" @card-share="cardShare" @card-release="cardRelease"
                  @card-edit="cardEdit" @card-delete="cardDelete" @card-statistics="cardStatistics"
                  @card-preview="cardPreview" @card-export="cardExport" @card-copy="cardCopy" @card-remove="cardRemove"
                  @card-restore="cardRestore">
                </card>
              </div>
            </div>
            <!-- 表格布局 -->
            <div v-show="isActive===2">
              <el-table :data="tableData" stripe style="width: 100%">
                <el-table-column prop="QName" label="问卷标题" width="250">
                </el-table-column>
                <el-table-column prop="type" label="问卷类型" width="120">
                  <template v-slot:default="slotProps">{{ formatType(slotProps.row.type) }}</template>
                </el-table-column>
                <el-table-column label="状态" width="100">
                  <template
                    v-slot:default="slotProps">{{ isShow === 1? formatStatus(slotProps.row.status) : '回收站'}}</template>
                </el-table-column>
                <el-table-column prop="count" label="回收量" width="120">
                </el-table-column>
                <el-table-column prop="CTime" label="创建时间" width="200">
                </el-table-column>
                <el-table-column label="截止时间" width="200">
                  <template slot-scope="scope">
                    <span>{{ scope.row.ETime === 'None' || isShow === 2? '未设置' : scope.row.ETime }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="220">
                  <template slot-scope="scope">
                    <el-button v-show="isShow === 1" size="mini" @click="handleRelease(scope.$index)">
                      {{ scope.row.status === 1 ? '暂停' : '开启' }}
                    </el-button>
                    <el-button v-show="isShow === 1" size="mini" @click="handleEdit(scope.$index)">编辑</el-button>
                    <el-button size="mini" type="primary" @click="handleStatistics(scope.$index)">统计</el-button>
                  </template>
                </el-table-column>
                <el-table-column label="更多功能">
                  <template slot-scope="scope">
                    <el-dropdown trigger="click" placement="bottom-start" @command="handleCommandForMore">
                      <span><i class="iconfont icon-more" style="cursor: pointer;"></i></span>
                      <el-dropdown-menu slot="dropdown" :visible-arrow="false">
                        <el-dropdown-item v-show="isShow === 1" :command="beforeHandleCommand(scope, '预览')">预览
                        </el-dropdown-item>
                        <el-dropdown-item v-show="isShow === 1" :command="beforeHandleCommand(scope, '分享')">分享
                        </el-dropdown-item>
                        <el-dropdown-item v-show="isShow === 1" :command="beforeHandleCommand(scope, '导出数据')">导出数据
                        </el-dropdown-item>
                        <el-dropdown-item v-show="isShow === 1" :command="beforeHandleCommand(scope, '复制')">复制
                        </el-dropdown-item>
                        <el-dropdown-item v-show="isShow === 1" :command="beforeHandleCommand(scope, '移动到回收站')">移动到回收站
                        </el-dropdown-item>
                        <el-dropdown-item v-show="isShow === 2" :command="beforeHandleCommand(scope, '恢复')">恢复
                        </el-dropdown-item>
                        <el-dropdown-item v-show="isShow === 2" :command="beforeHandleCommand(scope, '彻底删除')">彻底删除
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-main>
      </el-container>
    </el-container>
    <el-dialog title="问卷分享" :visible.sync="showDialog">
      分享链接:
      <div>
        <el-link type="primary" id="text" :href="getLink(QID64)">http://139.196.144.248:8080/#/answer/{{ QID64 }}
        </el-link>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="showDialog = false">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import card from "../components/manage/card";
import Answer from "./Answer.vue";
import AES from "../common/AES.js";

export default {
  name: "Manage",
  components: {
    card,
    Answer
  },
  data() {
    return {
      preview: {
        showPreview: false,
        previewQID64: -1
      },
      isShow: 1,
      title: "我的问卷",
      isActive: 1,
      showDialog: false,
      QID64: "",
      tableData: [
        {
          qid: 0,
          QName: "xxxxxxxxxxxxxx",
          CTime: "2021-08-21 22:00:00",
          count: 0,
          status: 1
        }
      ],
      searchInput: "",
      myQuestionnaires: [],
      recycledQuestionnaires: []
    };
  },
  methods: {
    getLink(QID) {
      // 获取连接
      return "http://139.196.144.248:8080/#/answer/" + QID;
    },
    /*-----卡片视图/列表视图切换方法-----*/
    cardView() {
      this.isActive = 1;
    },
    tableView() {
      this.isActive = 2;
    },
    /*-------------------------------*/

    /*-----问卷操作-----*/
    // 配置handleCommandForMore的参数
    beforeHandleCommand(scope, command) {
      return {
        scope: scope,
        command: command
      };
    },
    handleCommandForMore(command) {
      switch (command.command) {
        case "预览":
          this.handlePreview(command.scope.$index);
          break;
        case "分享":
          this.handleShare(command.scope.$index);
          break;
        case "导出数据":
          this.handleExport(command.scope.$index);
          break;
        case "复制":
          this.handleCopy(command.scope.$index);
          break;
        case "移动到回收站":
          this.handleRemove(command.scope.$index);
          break;
        case "恢复":
          this.handleRestore(command.scope.$index);
          break;
        case "彻底删除":
          this.handleDelete(command.scope.$index);
          break;
        default:
          break;
      }
    },
    // 问卷开启关闭
    changeStatus(oldStatus) {
      let newStatus;
      switch (oldStatus) {
        case 0:
          newStatus = 1;
          break;
        case 1:
          newStatus = 2;
          break;
        case 2:
          newStatus = 1;
          break;
        default:
          break;
      }
      return newStatus;
    },
    cardRelease(qid, oldStatus, index) {
      let newStatus = this.changeStatus(oldStatus);
      console.log(newStatus);
      this.$serve
        .changeStatus(qid, newStatus)
        .then(() => {
          this.$message.success("修改问卷状态成功");
          this.tableData[index].status = newStatus;
        })
        .catch(error => {
          console.log(error);
          alert("更改问卷状态失败");
        });
    },
    handleRelease(index) {
      var qid = this.tableData[index].qid;
      var oldStatus = this.tableData[index].status;
      this.cardRelease(qid, oldStatus, index);
    },
    // 编辑问卷
    cardEdit(qid) {
      this.$router.push({ path: "detail/surveyPage/" + qid });
    },
    handleEdit(index) {
      let qid = this.tableData[index].qid;
      this.cardEdit(qid);
    },
    // 问卷统计
    cardStatistics(qid) {
      this.$router.push({ path: "detail/statistic/" + qid });
    },
    handleStatistics(index) {
      let qid = this.tableData[index].qid;
      this.cardStatistics(qid);
    },
    // 移到回收站
    cardRemove(qid, index) {
      this.$serve.changeStatus(qid, -1).then(res => {
        if (res.status === 200) this.tableData.splice(index, 1);
      });
    },
    handleRemove(index) {
      this.cardRemove(this.tableData[index].qid, index);
    },
    // 恢复
    cardRestore(qid, index) {
      this.$serve.changeStatus(qid, 0).then(res => {
        if (res.status === 200) {
          this.tableData.splice(index, 1);
        }
      });
    },
    handleRestore(index) {
      this.cardRestore(this.tableData[index].qid, index);
    },
    // 删除问卷
    cardDelete(qid, index) {
      // 网络请求
      this.$serve
        .deleteQuestionnaire(qid)
        .then(res => {
          if (res.status === 200) {
            this.$message.success("删除成功");
            this.tableData.splice(index, 1);
          }
        })
        .catch(error => {
          console.log(error);
          alert("删除问卷失败");
        });
    },
    handleDelete(index) {
      let qid = this.tableData[index].qid;
      console.log(qid);
      this.cardDelete(qid, index);
    },
    // 问卷预览
    cardPreview(qid) {
      this.preview.showPreview = true;
      this.preview.previewQID64 = this.$AES.encrypt(qid);
    },
    handlePreview(index) {
      console.log(this.tableData[index].qid);
      this.cardPreview(this.tableData[index].qid);
    },
    // 问卷复制
    cardCopy(qid) {
      this.$serve.copyQuestionnaire(qid).then(res => {
        this.showMyQuestionnaire();
      });
    },
    handleCopy(index) {
      this.cardCopy(this.tableData[index].qid);
    },
    // 问卷统计导出
    cardExport(qid) {
      this.$serve.getSurveyAndAnswer(qid).then(res => {
        this.$mTool.exportAllAnswers(res.answers.data, res.survey.data);
      });
    },
    handleExport(index) {
      this.cardExport(this.tableData[index].qid);
    },
    // 问卷分享
    cardShare(qid) {
      let m = AES.encrypt(qid);
      this.QID64 = m.replace(/\//g, "BUAA");

      this.showDialog = true;
    },
    handleShare(index) {
      this.cardShare(this.tableData[index].qid);
    },
    /*----------------*/

    /*-----左侧导航栏-----*/
    // 新建问卷
    newQuestionnaire() {
      this.$router.push({ path: "choose" });
    },
    // 展示我的问卷
    showMyQuestionnaire() {
      this.isShow = 1;
      this.title = "我的问卷";
      this.$serve.getQuestionnaire(this.$store.state.userName).then(res => {
        this.myQuestionnaires = [];
        for (let item of res.data.root) {
          this.myQuestionnaires.push(item[0]);
        }
        this.tableData = this.myQuestionnaires;
      });
    },
    // 展示回收站
    showRecycleBin() {
      this.isShow = 2;
      this.title = "回收站";
      this.$serve.getRecycled(this.$store.state.userName).then(res => {
        this.recycledQuestionnaires = [];
        for (let item of res.data.root) {
          console.log(item);
          this.recycledQuestionnaires.push(item[0]);
        }
        console.log(this.recycledQuestionnaires);
        this.tableData = this.recycledQuestionnaires;
        console.log(this.tableData);
      });
    },
    /*------------------*/

    /*-----初始化数据-----*/
    formatStatus(oldStatus) {
      return this.$store.state.questionnaireStatus[oldStatus];
    },
    formatType(oldType) {
      let str = "普通问卷";
      switch (oldType) {
        case "normal":
          str = "普通问卷";
          break;
        case "vote":
          str = "投票问卷";
          break;
        case "sign":
          str = "报名问卷";
          break;
        case "exam":
          str = "考试问卷";
          break;
        case "location":
          str = "疫情打卡";
          break;
        default:
          break;
      }
      return str;
    },
    dataInit() {
      console.log("data init");
      this.showMyQuestionnaire();
    },
    /*------------------*/

    /*-----排序-----*/
    handleCommandForTime(command) {
      if (command === "a") this.orderByTime();
      else if (command === "b") this.reserveByTime();
    },
    handleCommandForCount(command) {
      if (command === "a") this.orderByCount();
      else if (command === "b") this.reserveByCount();
    },
    orderByTime() {
      if (this.tableData.length > 0)
        this.tableData.sort(function(a, b) {
          return Date.parse(a.CTime) - Date.parse(b.CTime);
        });
    },
    reserveByTime() {
      if (this.tableData.length > 0)
        this.tableData.sort(function(a, b) {
          return Date.parse(b.CTime) - Date.parse(a.CTime);
        });
    },
    orderByCount() {
      if (this.tableData.length > 0)
        this.tableData.sort(function(a, b) {
          return a.count - b.count;
        });
    },
    reserveByCount() {
      if (this.tableData.length > 0)
        this.tableData.sort(function(a, b) {
          return b.count - a.count;
        });
    },
    /*-------------*/

    /*-----搜索-----*/
    search() {
      this.tableData = this.myQuestionnaires;
      if (this.searchInput != null) {
        let temp = [];
        for (let item of this.tableData) {
          if (item.QName.search(this.searchInput) > -1) temp.push(item);
        }
        this.tableData = [];
        for (let item of temp) this.tableData.push(item);
      }
    }
    /*-------------*/
  },
  mounted() {
    this.dataInit();
  }
};
</script>

<style scoped>
.left-nav-wrap {
  width: 148px;
  height: calc(100vh - 80px);
  /*这个20算在height里，不是很理解*/
  padding-top: 20px;
}

.el-aside {
  border-right: 2px solid #dee2e6;
}

.nav-button {
  margin: 10px 0;
}

.navbuttonactive {
  color: #2378ff;
}

.no-border {
  background-color: transparent;
  border-color: transparent;
}

.manage-main {
  background-color: #e9ecef;
  padding: 0 20px;
}

.manage-content {
  overflow: auto;
}

.sub-header {
  padding: 24px 24px 24px 0;
  box-sizing: border-box;
  overflow: hidden;
}

.sub-header-mode {
  width: 62px;
  height: 30px;
  margin: auto 10px;
  background: white;
  border: 1px solid #e5e5e5;
  border-radius: 4px;
}

.sub-header-mode .active {
  background: #2378ff;
  box-shadow: 0 2px 4px 0 rgb(35 120 255);
  fill: white;
}

.sub-header-title {
  float: left;
  font-size: 18px;
  font-weight: 900;
  text-align: center;
  white-space: nowrap;
}

.sub-header-mode-btn {
  margin-top: -1px;
  width: 32px;
  height: 32px;
  display: inline-block;
  border-radius: 4px;
  cursor: pointer;
}

.btn-icon {
  font-size: 20px;
  line-height: 32px;
}

.btnActive {
  color: white;
}

.wrap {
  padding: 5px 24px;
  display: grid;
  justify-content: space-between;
  grid-template-columns: repeat(auto-fill, 230px);
  grid-gap: 24px;
}

.sort-mode {
  margin-top: 7px;
}

.sort-mode-btn {
  margin: 0 5px;
}

.sort-mode-title {
  font-size: 14px;
  text-align: center;
  white-space: nowrap;
}

.sort-mode-title,
.el-icon-d-caret {
  color: #a6a6a6;
  cursor: default;
}

.sort-mode-pop {
  border: transparent;
  margin: 0;
}

.search-input {
  height: 32px;
  margin: auto 5px;
}

.el-icon-search:hover {
  color: #2378ff;
  cursor: pointer;
}

.fl {
  float: right;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}
</style>